package com.zerowidth.db;

import java.sql.*;

public class DBConn {

    private static final String TAG = "DBinit";

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    // 数据库的用户名与密码，需要根据自己的设置
    private static final String USER = "root";
    private static final String PWD = "1524MKmk!";
    private static final String IP = "120.55.182.250";

    // --数据库实例的名称-- //
    public String SCHEMA = "mockDB";

    private String DB_URL = String.format(
            "jdbc:mysql://%s:3306/%s?useSSL=false&serverTimezone=UTC&autoReconnect=true&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true",
            IP,
            SCHEMA);


    private static final DBConn instance = new DBConn();

    public static DBConn getInst() {
        return instance;
    }

    private DBConn() {
        init();
    }

    private Connection conn = null;
    private Statement stmt = null;

    public Connection getCoon() {
        if (conn == null) {
            init();
        }
        return conn;
    }

    public Statement getStmt() {
        try {
            stmt = getCoon().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        } catch (Exception sqlException) {
            sqlException.printStackTrace();
            println(TAG + ", 创建stmt失败");
        }
        return stmt;
    }

    public void init() {
        println("init()...");

        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PWD);

            println("实例化Statement对象...");
            stmt = getCoon().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    public void release() {
        println("release()...");

        try {
            conn.close();
            stmt.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private void println(String msg) {
        System.out.println(TAG + ":" + msg);
    }

}
